package com.example.ordermealservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.commonutils.JwtUtils;
import com.example.commonutils.R;
import com.example.commonutils.handler.NoqueueException;
import com.example.commonutils.vo.ShoppingCartCommon;
import com.example.ordermealservice.entity.OrderDish;
import com.example.ordermealservice.entity.OrderShoppingCart;
import com.example.ordermealservice.entity.vo.ShoppingCartVo;
import com.example.ordermealservice.service.OrderDishService;
import com.example.ordermealservice.service.OrderShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-07-05
 */
@RestController
@RequestMapping("/ordermealservice/shoppingcart")
public class OrderShoppingcartController {
    @Autowired
    private OrderShoppingCartService orderShoppingCartService;
    @Autowired
    private OrderDishService orderDishService;
    //加入购物车
    @PutMapping("/addToCart/{dishId}")
    public R addToCart(HttpServletRequest request, @PathVariable String dishId){
        //调用jwt工具类的方法，根据request对象获取头信息，返回用户id
        String customerId = JwtUtils.getMemberIdByJwtToken(request);
        LambdaQueryWrapper<OrderShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderShoppingCart::getCustomerId,customerId);
        queryWrapper.eq(OrderShoppingCart::getDishId,dishId);
        OrderShoppingCart one = orderShoppingCartService.getOne(queryWrapper);
        if (null != one){
            Integer copies = one.getCopies();
            //将copies与菜品的库存比较，如果小于库存，则加购失败
            if (null != dishId){
                OrderDish dish = orderDishService.getById(dishId);
                if (copies >= dish.getDishNumber()){
                    return R.error().message("该菜品不能购买更多了");
                }
            }
            copies ++;
            one.setCopies(copies);
            orderShoppingCartService.updateById(one);
        }else {
            OrderShoppingCart orderShoppingCart = new OrderShoppingCart();
            orderShoppingCart.setCustomerId(customerId);
            orderShoppingCart.setCopies(1);
            orderShoppingCart.setDishId(dishId);
            orderShoppingCartService.save(orderShoppingCart);
        }
        return R.ok();
    }
    //减少购物车中商品的数量
    @PutMapping("/subFromCart/{dishId}")
    public R subFromCart(HttpServletRequest request, @PathVariable String dishId){
        //调用jwt工具类的方法，根据request对象获取头信息，返回用户id
        String customerId = JwtUtils.getMemberIdByJwtToken(request);
        LambdaQueryWrapper<OrderShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderShoppingCart::getCustomerId,customerId);
        queryWrapper.eq(OrderShoppingCart::getDishId,dishId);
        OrderShoppingCart one = orderShoppingCartService.getOne(queryWrapper);
        Integer copies = one.getCopies();
        if (copies == 1){
            return R.error().message("数量不能再减少了！");
        }
        copies --;
        one.setCopies(copies);
        orderShoppingCartService.updateById(one);
        return R.ok();
    }
    //查看购物车
    @GetMapping("/queryShoppingCart")
    public R queryShoppingCart(HttpServletRequest request){
        String customerId = JwtUtils.getMemberIdByJwtToken(request);
        LambdaQueryWrapper<OrderShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderShoppingCart::getCustomerId,customerId);
        List<OrderShoppingCart> list = orderShoppingCartService.list(queryWrapper);
        //查看购物车并不是要看dishId，而是通过dishId查看菜品的图片、名称、价格、所需时间和加入的数量
        ArrayList<ShoppingCartVo> arrayList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ShoppingCartVo shoppingCartVo = new ShoppingCartVo();
            String dishId = list.get(i).getDishId();
            Integer copies = list.get(i).getCopies();
            OrderDish dish = orderDishService.getById(dishId);
            BeanUtils.copyProperties(dish,shoppingCartVo);
            shoppingCartVo.setCopies(copies);
            arrayList.add(shoppingCartVo);
        }
        return R.ok().data("shoppingCart",arrayList);
    }
    //从购物车中移除
    @DeleteMapping("/deleteFromShoppingCart")
    public R deleteFromShoppingCart(HttpServletRequest request,@RequestParam List<String> ids){
        String customerId = JwtUtils.getMemberIdByJwtToken(request);
        if (ids.size()==0){
            return R.error().message("请选中需要删除的菜品");
        }
        LambdaQueryWrapper<OrderShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OrderShoppingCart::getDishId,ids);
        queryWrapper.eq(OrderShoppingCart::getCustomerId,customerId);
        orderShoppingCartService.remove(queryWrapper);
        return R.ok();
    }
    //为了方便，这里再定义一个通过购物车id来删除购物车数据的方法
    @DeleteMapping("/deleteFromShoppingCartById")
    public R deleteFromShoppingCartById(@RequestParam List<String> ids){
        LambdaQueryWrapper<OrderShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OrderShoppingCart::getId,ids);
        orderShoppingCartService.remove(queryWrapper);
        return R.ok();
    }
    //通过菜品id和用户id查询购物车数据的id，该id作为参数传给结算功能(因为存入购物车的id是dishId,而用于结算的id是购物车的id)
    @GetMapping("/queryShoppingCartId")
    public R queryShoppingCartId(HttpServletRequest request
            ,@RequestParam List<String> dishIds){
        String customerId = JwtUtils.getMemberIdByJwtToken(request);
        if (dishIds.size()==0){
            throw new NoqueueException(20001,"请选择需要结算的项目");
        }
        LambdaQueryWrapper<OrderShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderShoppingCart::getCustomerId,customerId);
        queryWrapper.in(OrderShoppingCart::getDishId,dishIds);
        List<OrderShoppingCart> list = orderShoppingCartService.list(queryWrapper);
        List<String> ids = new ArrayList<>();
        for (OrderShoppingCart orderShoppingCart : list) {
            ids.add(orderShoppingCart.getId());
        }
        return R.ok().data("ids",ids);
    }

    //通过购物车id和菜品id获取购物车中该菜品的名称、数量并计算出总价
    @GetMapping("/queryShoppingCartInfo/{id}")
    public ShoppingCartCommon queryShoppingCartInfo(@PathVariable String id){
        OrderShoppingCart shoppingCart = orderShoppingCartService.getById(id);
        Integer copies = shoppingCart.getCopies();
        String dishId = shoppingCart.getDishId();
        OrderDish dish = orderDishService.getById(dishId);
        BigDecimal dishPrice = dish.getDishPrice();
        String dishName = dish.getDishName();
        BigDecimal totalAmount = dishPrice.multiply(BigDecimal.valueOf(copies));
        ShoppingCartCommon shoppingCartCommon = new ShoppingCartCommon();
        shoppingCartCommon.setCopies(copies);
        shoppingCartCommon.setDishName(dishName);
        shoppingCartCommon.setPrice(dishPrice);
        shoppingCartCommon.setTotalAmount(totalAmount);
        shoppingCartCommon.setDishId(dishId);
        return shoppingCartCommon;
    }
    //通过id查询菜品的库存
    @GetMapping("/queryDishNumById/{id}")
    public Integer queryDishNumById(@PathVariable String id){
        OrderDish dish = orderDishService.getById(id);
        return dish.getDishNumber();
    }
}
